#!/usr/bin/python
import logging
import os
import sys

from functools import partial

from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.net import Mininet
from mininet.node import Host, RemoteController
from mininet.topo import Topo
from mininet.util import dumpNodeConnections


HOST_TO_USER = {
    "h1": "d1",
    "h2": "d_srv1",
    "h3": "d_srv2",

    "h4": "f1",
    "h5": "f2",
    "h6": "f_srv1",

    "h7": "p1",
    "h8": "p2",
    "h9": "p_srv1",

    "h10": "c1",
    "h11": "c2",
    "h12": "c_srv1"
}


class ExampleCorpTopo(Topo):
    def build(self):
        # Core switch (s1) and edge switches (s2-s5)
        s1 = self.addSwitch("s1")
        s2 = self.addSwitch("s2")
        s3 = self.addSwitch("s3")
        s4 = self.addSwitch("s4")
        s5 = self.addSwitch("s5")

        self.addLink(s1, s2)
        self.addLink(s1, s3)
        self.addLink(s1, s4)
        self.addLink(s1, s5)

        # Develop
        h1 = self.addHost("h1")
        self.addLink(h1, s2)
        h2 = self.addHost("h2")
        self.addLink(h2, s2)
        h3 = self.addHost("h3")
        self.addLink(h3, s2)



        # Front end
        h4 = self.addHost("h4")
        self.addLink(h4, s3)
        h5 = self.addHost("h5")
        self.addLink(h5, s3)

        h6 = self.addHost("h6")
        self.addLink(h6, s3)


        # PM
        h7 = self.addHost("h7")
        self.addLink(h7, s4)
        h8 = self.addHost("h8")
        self.addLink(h8, s4)

        h9 = self.addHost("h9")
        self.addLink(h9, s4)


        # zibenjia
        h10 = self.addHost("h10")
        self.addLink(h10, s5)
        h11 = self.addHost("h11")
        self.addLink(h11, s5)
        h12 = self.addHost("h12")
        self.addLink(h12, s5)


def launch_network():
    "Create and test a simple network"
    topo = ExampleCorpTopo()
    private_dirs = ["/tmp", "/etc/wpa_supplicant", "/var/log", "/var/run"]
    host = partial(Host, privateDirs=private_dirs)
    net = Mininet(topo=topo, host=host, controller=RemoteController)
    net.start()

    for host in net.hosts:
        conf = """
        ap_scan=0
        eapol_version=2
        network={
           key_mgmt=IEEE8021X
           eap=MD5
           identity="%s"
           password="%s"
           eapol_flags=0
        }
        """ % (HOST_TO_USER[host.name], "TIS")

        host.cmd("echo '%s' > /etc/wpa_supplicant/wpa_supplicant.conf" % conf)

        if_name = host.name + "-eth0"
        host.cmdPrint("wpa_supplicant -B -Dwired -i%s"
                      " -c/etc/wpa_supplicant/wpa_supplicant.conf" % if_name)

    print("Dumping host connections")
    dumpNodeConnections(net.hosts)

    CLI(net)

    # Run "px net.pingAll(timeout=1)" in CLI to test connectivity

    for host in net.hosts:
        host.cmd("killall wpa_supplicant")
    net.stop()


if __name__ == "__main__":
    setLogLevel("info")
    launch_network()
